package com.zy.rpc.server.handle;

import com.zy.rpc.common.ask.RpcRequest;
import com.zy.rpc.common.ask.RpcResponse;
import com.zy.rpc.server.cache.LocalServerCache;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.threads.ThreadPoolExecutor;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author zy
 * @date 2023/4/30 17:30
 */

@Slf4j
public class RpcHandle extends SimpleChannelInboundHandler<RpcRequest> {
    private final ThreadPoolExecutor threadPoolExecutor=new ThreadPoolExecutor(10,10,60l, TimeUnit.SECONDS,new ArrayBlockingQueue<>(1000));
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcRequest r) throws Exception {
        System.out.println("收到消息");
            threadPoolExecutor.submit(()->{
                RpcResponse rpcResponse = new RpcResponse();
                Object object = getObject(r);
                rpcResponse.setData(object);
                ChannelFuture channelFuture = ctx.writeAndFlush(rpcResponse);
            });
    }

    public Object getObject(RpcRequest rpcRequest)  {
        try {
            Object bean = LocalServerCache.get(rpcRequest.getServiceName());
            if (bean==null) {throw new RuntimeException("没有此服务方法");}
            Method method = bean.getClass().getMethod(rpcRequest.getMethod(), rpcRequest.getParamsType());

            Object invoke = method.invoke(bean, rpcRequest.getParams());
            return invoke;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
